package com.outdoor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.outdoor.exception.BusinessException;
import com.outdoor.model.dto.request.TeamCreateRequest;
import com.outdoor.model.entity.Team;
import com.outdoor.model.entity.TeamMember;
import com.outdoor.model.entity.User;
import com.outdoor.model.enums.ActivityType;
import com.outdoor.mapper.TeamMapper;
import com.outdoor.mapper.TeamMemberMapper;
import com.outdoor.service.TeamService;
import com.outdoor.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 团队服务实现
 * 
 * @author OutdoorTeam
 * @date 2025-05-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeamServiceImpl implements TeamService {

    private final TeamMapper teamMapper;
    private final TeamMemberMapper teamMemberMapper;
    private final UserService userService;

    @Override
    public Team createTeam(TeamCreateRequest request, Long leaderId) {
        User leader = userService.getUserById(leaderId);
        Team team = Team.builder()
                .name(request.getName())
                .activityType(request.getActivityType())
                .location(request.getLocation())
                .date(request.getDate())
                .maxMembers(request.getMaxMembers())
                .description(request.getDescription())
                .experienceLevel(request.getExperienceLevel())
                .additionalRequirements(request.getAdditionalRequirements())
                .leaderId(leaderId)
                .build();
        teamMapper.insert(team);
        
        // 领队自动成为成员，添加到团队成员关联表
        TeamMember teamMember = TeamMember.builder()
                .teamId(team.getId())
                .userId(leaderId)
                .joinTime(LocalDateTime.now())
                .build();
        teamMemberMapper.insert(teamMember);
        
        log.info("团队创建成功: {}, 领队: {}", team.getName(), leader.getUsername());
        return team;
    }

    @Override
    public Team getTeamById(Long id) {
        Team team = teamMapper.selectById(id);
        if (team == null) {
            throw new BusinessException("TEAM_NOT_FOUND", "团队不存在");
        }
        return team;
    }

    @Override
    public Team updateTeam(Long id, TeamCreateRequest request, Long currentUserId) {
        Team team = getTeamById(id);
        if (!team.getLeaderId().equals(currentUserId)) {
            throw new BusinessException("UNAUTHORIZED", "只有团队领队可以更新团队信息");
        }
        team.setName(request.getName());
        team.setActivityType(request.getActivityType());
        team.setLocation(request.getLocation());
        team.setDate(request.getDate());
        team.setMaxMembers(request.getMaxMembers());
        team.setDescription(request.getDescription());
        team.setExperienceLevel(request.getExperienceLevel());
        team.setAdditionalRequirements(request.getAdditionalRequirements());
        teamMapper.updateById(team);
        log.info("团队更新成功: {}", team.getName());
        return team;
    }

    @Override
    public void deleteTeam(Long id, Long currentUserId) {
        Team team = getTeamById(id);
        if (!team.getLeaderId().equals(currentUserId)) {
            throw new BusinessException("UNAUTHORIZED", "只有团队领队可以删除团队");
        }
        
        // 删除团队成员关系
        QueryWrapper<TeamMember> memberQuery = new QueryWrapper<>();
        memberQuery.eq("team_id", id);
        teamMemberMapper.delete(memberQuery);
        
        // 删除团队
        teamMapper.deleteById(id);
        log.info("团队删除成功: {}", team.getName());
    }

    @Override
    public IPage<Team> getTeamsByLeader(Long userId, Page<Team> page) {
        QueryWrapper<Team> query = new QueryWrapper<>();
        query.eq("leader_id", userId);
        return teamMapper.selectPage(page, query);
    }

    @Override
    public IPage<Team> getTeamsByMember(Long userId, Page<Team> page) {
        // 在这里实现查询用户参与的团队的分页列表
        // 需要通过TeamMember表进行关联查询
        // 实际项目中可以使用自定义SQL或者子查询实现
        List<Long> teamIds = getTeamIdsByMember(userId);
        if (teamIds.isEmpty()) {
            // 如果没有参与任何团队，返回空页
            return page.setRecords(new ArrayList<>());
        }
        QueryWrapper<Team> query = new QueryWrapper<>();
        query.in("id", teamIds);
        return teamMapper.selectPage(page, query);
    }

    @Override
    public IPage<Team> findTeams(ActivityType activityType, String location, LocalDate startDate, LocalDate endDate, String keyword, Page<Team> page) {
        QueryWrapper<Team> query = new QueryWrapper<>();
        if (activityType != null && activityType != ActivityType.ALL) {
            query.eq("activity_type", activityType);
        }
        if (location != null && !location.isEmpty()) {
            query.like("location", location);
        }
        if (startDate != null) {
            query.ge("date", startDate);
        }
        if (endDate != null) {
            query.le("date", endDate);
        }
        // 添加关键词搜索，模糊匹配团队名称或地点
        if (keyword != null && !keyword.trim().isEmpty()) {
            query.and(wrapper -> wrapper.like("name", keyword.trim()).or().like("location", keyword.trim()));
        }
        return teamMapper.selectPage(page, query);
    }

    @Override
    public Team joinTeam(Long teamId, Long userId) {
        Team team = getTeamById(teamId);
        User user = userService.getUserById(userId);
        
        // 查询团队当前成员数
        QueryWrapper<TeamMember> countQuery = new QueryWrapper<>();
        countQuery.eq("team_id", teamId);
        long memberCount = teamMemberMapper.selectCount(countQuery);
        
        // 检查团队是否已满
        if (memberCount >= team.getMaxMembers()) {
            throw new BusinessException("TEAM_FULL", "团队已满，无法加入");
        }
        
        // 检查用户是否已在团队中
        QueryWrapper<TeamMember> memberQuery = new QueryWrapper<>();
        memberQuery.eq("team_id", teamId).eq("user_id", userId);
        if (teamMemberMapper.selectCount(memberQuery) > 0) {
            throw new BusinessException("ALREADY_MEMBER", "用户已是团队成员");
        }
        
        // 添加成员关系
        TeamMember teamMember = TeamMember.builder()
                .teamId(teamId)
                .userId(userId)
                .joinTime(LocalDateTime.now())
                .build();
        teamMemberMapper.insert(teamMember);
        
        log.info("用户 {} 成功加入团队: {}", user.getUsername(), team.getName());
        return team;
    }

    @Override
    public Team leaveTeam(Long teamId, Long userId) {
        Team team = getTeamById(teamId);
        User user = userService.getUserById(userId);
        
        // 检查是否是领队
        if (team.getLeaderId().equals(userId)) {
            throw new BusinessException("LEADER_CANNOT_LEAVE", "团队领队不能退出团队，请先转让领队权限或解散团队");
        }
        
        // 检查用户是否在团队中
        QueryWrapper<TeamMember> memberQuery = new QueryWrapper<>();
        memberQuery.eq("team_id", teamId).eq("user_id", userId);
        if (teamMemberMapper.selectCount(memberQuery) == 0) {
            throw new BusinessException("NOT_MEMBER", "用户不是团队成员");
        }
        
        // 删除成员关系
        teamMemberMapper.delete(memberQuery);
        
        log.info("用户 {} 成功退出团队: {}", user.getUsername(), team.getName());
        return team;
    }
    
    @Override
    public List<Long> getTeamMemberIds(Long teamId) {
        QueryWrapper<TeamMember> query = new QueryWrapper<>();
        query.eq("team_id", teamId).select("user_id");
        return teamMemberMapper.selectList(query).stream()
                .map(TeamMember::getUserId)
                .toList();
    }
    
    /**
     * 获取团队成员列表
     * 
     * @param teamId 团队ID
     * @return 成员列表
     */
    public List<User> getTeamMembers(Long teamId) {
        List<Long> memberIds = getTeamMemberIds(teamId);
        if (memberIds.isEmpty()) {
            return new ArrayList<>();
        }
        return userService.getUsersByIds(memberIds);
    }
    
    /**
     * 获取用户参与的团队ID列表
     * 
     * @param userId 用户ID
     * @return 团队ID列表
     */
    private List<Long> getTeamIdsByMember(Long userId) {
        QueryWrapper<TeamMember> query = new QueryWrapper<>();
        query.eq("user_id", userId).select("team_id");
        return teamMemberMapper.selectList(query).stream()
                .map(TeamMember::getTeamId)
                .toList();
    }

    /**
     * 更新团队关联行程
     * 
     * @param team 团队
     */
    public void updateTeamTrip(Team team) {
        teamMapper.updateById(team);
        log.info("团队行程更新成功: {}", team.getName());
    }
    
    @Override
    public List<Long> getTeamIdsByLeader(Long userId) {
        QueryWrapper<Team> query = new QueryWrapper<>();
        query.eq("leader_id", userId)
             .select("id");
        List<Team> teams = teamMapper.selectList(query);
        
        List<Long> teamIds = new ArrayList<>();
        for (Team team : teams) {
            teamIds.add(team.getId());
        }
        return teamIds;
    }
} 